<template>
  <div>
    <a-card :style="{ width: '100%' }">
      <a-alert type="warning" style="margin: 20px 0; padding: 20px"
        >为了方便在创建直播间时从选择商品，请尽量提前提审直播商品</a-alert
      >
      <a-form ref="liveFormRef" :model="liveForm" :style="{ width: '600px' }">
        <a-form-item label="直播标题" field="name" :rules="[REQUIRED]">
          <a-input v-model="liveForm.name" :disabled="liveStatus != 'NEW'" />
          <template #extra
            ><div class="tips"
              >直播间名字，最短3个汉字，最长17个汉字，1个汉字相当于2个字符</div
            ></template
          >
        </a-form-item>
        <a-form-item label="主播昵称" field="anchorName" :rules="[REQUIRED]">
          <a-input
            v-model="liveForm.anchorName"
            :disabled="liveStatus != 'NEW'"
          />
          <template #extra
            ><div class="tips"
              >主播昵称，最短2个汉字，最长15个汉字，1个汉字相当于2个字符</div
            ></template
          >
        </a-form-item>
        <a-form-item label="直播时间" field="startTime" :rules="[REQUIRED]">
          <!-- <a-range-picker @change="handleChangeTime" :disabled="disabled" show-time format="YYYY-MM-DD HH:mm" v-model="liveForm.rangeTime" style="width: 254px; marginBottom: 20px;" /> -->
          <a-range-picker
            v-model="liveForm.rangeTime"
            :disabled="liveStatus != 'NEW'"
            style="width: 360px"
            show-time
            format="YYYY-MM-DD HH:mm"
            @change="handleChangeTime"
          ></a-range-picker>
          <template #extra
            ><div class="tips"
              >直播开播时间需要在当前时间的10分钟后并且，开始时间不能在6个月后，直播计划结束时间（开播时间和结束时间间隔不得短于30分钟，不得超过24小时）</div
            ></template
          >
        </a-form-item>
        <a-form-item
          label="主播微信号"
          field="anchorWechat"
          :rules="[REQUIRED]"
        >
          <a-input
            v-model="liveForm.anchorWechat"
            :disabled="liveStatus != 'NEW'"
            placeholder="主播微信号"
          />
          <template #extra>
            <div class="tips"
              >主播微信号，如果未实名认证，需要先前往“小程序直播”小程序进行<a
                target="_black"
                href="https://res.wx.qq.com/op_res/9rSix1dhHfK4rR049JL0PHJ7TpOvkuZ3mE0z7Ou_Etvjf-w1J_jVX0rZqeStLfwh"
                >实名验证</a
              ></div
            >
          </template>
        </a-form-item>
        <!-- 分享卡片 -->
        <a-form-item field="feedsImg" label="分享卡片封面" :rules="[REQUIRED]">
          <a-image
            style="margin: 0 5px 5px 0"
            width="120"
            height="120"
            :src="liveForm.feedsImg"
          ></a-image>
          <div style="display: flex; justify-content: flex-start"
            ><a-button type="primary" @click="handleClickOssManages('feedsImg')"
              >上传图片</a-button
            ></div
          >
          <template #extra
            >直播间分享图，图片规则：建议像素800*640，大小不超过1M；</template
          >
        </a-form-item>
        <a-form-item field="coverImg" label="直播间背景墙" :rules="[REQUIRED]">
          <a-image
            style="margin: 0 5px 5px 0"
            width="120"
            height="120"
            :src="liveForm.coverImg"
          ></a-image>
          <div style="display: flex; justify-content: flex-start"
            ><a-button type="primary" @click="handleClickOssManages('coverImg')"
              >上传图片</a-button
            ></div
          >
          <template #extra
            >直播间背景图，图片规则：建议像素1080*1920，大小不超过1M</template
          >
        </a-form-item>
        <a-form-item field="shareImg" label="直播间分享图" :rules="[REQUIRED]">
          <a-image
            style="margin: 0 5px 5px 0"
            width="120"
            height="120"
            :src="liveForm.shareImg"
          ></a-image>
          <div style="display: flex; justify-content: flex-start"
            ><a-button type="primary" @click="handleClickOssManages('shareImg')"
              >上传图片</a-button
            ></div
          >
          <template #extra
            >直播间分享图，图片规则：建议像素800*640，大小不超过1M</template
          >
        </a-form-item>
        <a-form-item v-if="route.query.id" label="商品" :rules="[REQUIRED]">
          <div>
            <a-button
              v-if="liveStatus == 'NEW'"
              type="primary"
              @click="addGoods"
              >添加商品</a-button
            >
            <a-table
              class="goods-table"
              :columns="columns"
              :data="liveData"
              :pagination="false"
            >
              <template #goodsName="{ record, rowIndex }">
                <div class="flex-goods">
                  <a-badge
                    v-if="rowIndex == 0 || rowIndex == 1"
                    status="danger"
                  />
                  <img
                    class="thumbnail"
                    :src="record.thumbnail || record.goodsImage"
                  />{{ record.goodsName || record.name }}
                </div>
              </template>
              <template #price="{ record }">
                <div>
                  <div v-if="record.priceType == 1">{{
                    unitPrice(record.price, '￥')
                  }}</div>
                  <div v-if="record.priceType == 2"
                    >{{ unitPrice(record.price, '￥') }} 至
                    {{ unitPrice(record.price2, '￥') }}</div
                  >
                  <div v-if="record.priceType == 3"
                    >{{ unitPrice(record.price2, '￥')
                    }}<span class="original-price">{{
                      unitPrice(record.price2, '￥')
                    }}</span></div
                  >
                </div>
              </template>
              <template #quantity="{ record }"
                ><div>{{ record.quantity }}</div></template
              >
              <template #action="{ record, rowIndex }">
                <div class="action">
                  <a-button
                    style="margin-right: 10px"
                    :disabled="liveStatus != 'NEW'"
                    @click="deleteGoods(record, rowIndex)"
                    >删除</a-button
                  >
                  <!-- <a-button style="margin-right:10px;" @click="onMove(record.id,1)" :disabled="liveStatus != 'NEW'">上移</a-button>
                <a-button style="margin-right:10px;" @click="onMove(record.id,0)" :disabled="liveStatus != 'NEW'">下移</a-button> -->
                </div>
              </template>
            </a-table>
          </div>
          <template #extra
            ><div class="tips"
              >直播间商品中前两个商品将自动被选为封面，伴随直播间在直播列表中显示</div
            ></template
          >
        </a-form-item>
        <a-form-item>
          <a-button
            v-if="liveStatus == 'NEW'"
            type="primary"
            @click="createLives"
            >保存</a-button
          >
        </a-form-item>
      </a-form>
    </a-card>
    <a-modal v-model:visible="liveGoodsVisible" :width="1000">
      <template #title>商品选择</template>
      <!-- <liveGoods ref="liveGoodsRef" @callback="selectedGoodsData"></liveGoods> -->
    </a-modal>

    <!--上传图片弹框-->
    <a-modal
      v-model:visible="showOssManages"
      :width="966"
      title="选择图片"
      :body-style="{ paddingTop: '0px', paddingBottom: '0px' }"
      @ok="ossManagesOk"
      @cancel="showOssManages = false"
    >
      <ossManages
        :initialize="showOssManages"
        @selected="ossManagesSelected"
      ></ossManages>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import {
    getLiveGoods,
    getLiveInfo,
    addLive,
    editLive,
    delRoomLiveGoods,
    addLiveGoods,
  } from '@/api/promotion';
  import { unixToDate, unitPrice } from '@/utils/filters';
  import uploadFile from '@/api/common';
  import store from '@/utils/storage';
  import liveGoods from '@/views/promotion/live-goods/list.vue';
  import { Message } from '@arco-design/web-vue';
  import { REQUIRED, VARCHAR20 } from '@/utils/validator';
  import ossManages from '@/components/oss-manages/index.vue';

  // 携带toekn
  const accessToken = ref(store.getAccessToken());
  const liveGoodsRef = ref(null) as any; // 选择会员
  const liveGoodsVisible = ref(false);
  const fileFormat = ref<Array<string>>(['jpg', 'jpeg', 'png', 'gif', 'bmp']);
  const route = useRoute();
  const router = useRouter();
  const disabled = ref(route.query.id) as any;
  const liveStatus = ref('NEW');
  const liveFormRef = ref();
  const liveForm = ref<any>({
    name: '', // 直播标题
    anchorName: '', // 主播昵称
    anchorWechat: '', // 主播微信号
    feedsImg: '', // 分享卡片封面
    coverImg: '', // 直播间背景墙
    shareImg: '', // 分享图
    startTime: '',
    rangeTime: [],
  });
  const columns = [
    {
      title: '商品',
      dataIndex: 'goodsName',
      width: 300,
      slotName: 'goodsName',
    },
    {
      title: '价格',
      dataIndex: 'price',
      width: 200,
      slotName: 'price',
    },
    {
      title: '库存',
      dataIndex: 'quantity',
      slotName: 'quantity',
      width: 100,
    },
    {
      title: '操作',
      dataIndex: 'action',
      slotName: 'action',
      width: 300,
    },
  ];

  const liveData = ref<any>([]); // 直播商品集合

  const showOssManages = ref(false); // 上传图片弹框
  const ossManagesType = ref(); // 上传图片类型 goods商品图片，sku商品规格图片
  const ossManagesList = ref<Array<any>>([]);
  // 点击上传图片按钮
  const handleClickOssManages = (type: any) => {
    showOssManages.value = true;
    ossManagesType.value = type;
  };
  // 从子组件获取选择的图片
  const ossManagesSelected = (value: any) => {
    ossManagesList.value = value;
  };
  // 上传图片弹框确认
  const ossManagesOk = () => {
    showOssManages.value = false;
    if (ossManagesList.value && ossManagesList.value.length > 1) {
      Message.warning('只能上传一张图片！');
    } else {
      liveForm.value[ossManagesType.value] = ossManagesList.value[0].url;
      // if (ossManagesType.value === 'feedsImg' && ossManagesList.value.length) {
      //
      // } else {
      //   // coverImg
      // }
    }
  };

  const getLiveDetail = async () => {
    if (!route.query.id) {
      console.log(111);
    } else {
      const res = await getLiveInfo(route.query.id);
      if (res.data.success) {
        const data = res.data.result;
        liveForm.value = data;
        liveData.value = data.commodityList;
        liveForm.value.rangeTime = [
          unixToDate(data.startTime),
          unixToDate(data.endTime),
        ];
        liveStatus.value = data.status;
      }
    }
  };
  // 添加商品
  const addGoods = () => {
    liveGoodsRef.value.selectedMember = false;
    liveGoodsVisible.value = true;
  };
  // 删除直播间商品
  const deleteGoods = async (val: any, index: any) => {
    const res = await delRoomLiveGoods(liveForm.value.roomId, val.liveGoodsId);
    if (res.data.success) {
      Message.success('删除成功');
      liveData.value.splice(index, 1);
    }
  };
  // 上下移动功能
  // idr 1为上，0为下
  // const onMove = (code,dir) => {
  //   const moveComm = (curIndex:any,nextIndex:any) => {
  //     let arr = liveData.value
  //     arr[curIndex] = arr.splice(nextIndex,1,arr[curIndex])[0]
  //     // return arr;
  //   }
  //   liveData.value.some((val,index)=>{
  //     console.log(val,'vallllllll')
  //     if(val.id == code){
  //       if(dir == 1 && index == 0){
  //         Message.warning("已经顶部！")
  //       }else if(dir == 0 && index && liveData.value.length -1){
  //         Message.warning("已在底部")
  //       }else{
  //         let nextIndex = dir === 1 ? index - 1 : index + 1
  //         liveData.value = moveComm(index,nextIndex)
  //       }
  //     }
  //   })
  // }
  // 分享卡片封面上传成功回调
  const handleFeedsImgSuccess = (res: any) => {
    if (res.response.success) {
      Message.success('成功');
      liveForm.value.feedsImg = res.response.result;
    }
  };
  // 直播间背景图上传成功回调
  const handleCoverImgSuccess = (res: any) => {
    if (res.response.success) {
      Message.success('成功');
      liveForm.value.coverImg = res.response.result;
    }
  };
  // 直播间分享图上传成功回调
  const handleShareImgSuccess = (res: any) => {
    if (res.response.success) {
      Message.success('成功');
      liveForm.value.shareImg = res.response.result;
    }
  };
  // 上传失败
  const handleError = (res: any) => {
    Message.error('上传失败');
  };
  // 上传前校验
  const beforeUpload = (file: any) => {
    return new Promise((resolve, reject) => {
      if (
        !fileFormat.value.includes(
          file.name.split('.')[file.name.split('.').length - 1]
        )
      ) {
        reject(new Error('上传失败'));
        Message.error(`请选择 .jpg .jpeg .png .gif .bmp格式文件`);
      } else if (Number((file.size / 1024).toFixed(0)) > 1024) {
        reject(new Error('上传失败'));
        Message.error(`所选文件大小过大, 不得超过1M`);
      } else {
        resolve(true);
      }
    });
  };
  const createLives = async () => {
    const auth = await liveFormRef.value?.validate();
    if (!auth) {
      if (route.query.id) {
        liveForm.value.commodityList = JSON.stringify(liveData.value);
        delete liveForm.value.updateTime;
        editLive(liveForm.value).then((res: any) => {
          if (res.data.success) {
            Message.success('修改成功');
            router.push({ name: 'live' });
          }
        });
      } else {
        // 此处为创建直播
        // delete liveForm.value.rangeTime
        const params = JSON.parse(JSON.stringify(liveForm.value));
        delete params.rangeTime;
        console.log('创建直播', params);
        addLive(params).then((res: any) => {
          if (res.data.success) {
            console.log(liveForm.value, 'addLive');
            Message.success('添加成功');
            router.push({ name: 'live' });
          }
        });
      }
    }
  };
  const tipsDateError = () => {
    Message.error(
      '直播开播时间需要在当前时间的10分钟后并且，开始时间不能在6个月后，直播计划结束时间（开播时间和结束时间间隔不得短于30分钟，不得超过24小时）'
    );
  };
  // 选择时间后得回调
  const handleChangeTime = (daterange: any) => {
    console.log(daterange, 'daterange');
    // 直播开播时间需要在当前时间得10分钟后
    // 此处设置默认为15分钟方便调整
    const siteTime = new Date().getTime() / 1000;
    const selectTIme = new Date(daterange[0]).getTime() / 1000;
    // const currentTime = unixToDate(siteTime) ;
    // 开播时间和结束时间间隔不得短于30分钟，不得超过24小时
    // 判断用户设置得结束时间
    const endTime = new Date(daterange[1]).getTime() / 1000;
    if (selectTIme <= siteTime + 15 * 60) {
      tipsDateError();
    } else if (selectTIme + 30 * 60 >= endTime) {
      // 不能小于30分钟
      tipsDateError();
    } else if (selectTIme + 24 * 60 * 60 <= endTime) {
      // 不能超过24小时
      tipsDateError();
    } else if (
      siteTime >=
      new Date().getTime() + 6 * 31 * 24 * 3600 * 1000 + 86400000
    ) {
      tipsDateError();
    } else {
      liveForm.value.startTime = new Date(daterange[0]).getTime() / 1000;
      liveForm.value.endTime = new Date(daterange[1]).getTime() / 1000;
    }
  };
  const callBackData = (way: any) => {
    liveGoodsVisible.value = false;
    addLiveGoods({
      roomId: route.query.roomId,
      liveGoodsId: way.liveGoodsId,
      goodsId: way.goodsId,
    }).then((res) => {
      if (res.data.success) {
        liveData.value.push(way);
        console.log(liveData.value, 'liveData');
      }
    });
  };
  const selectedGoodsData = (goods: any) => {
    console.log(goods, 'goodssss');
    liveData.value.push({ ...goods });
  };
  onMounted(() => {
    getLiveDetail();
  });
</script>

<style lang="less" scoped>
  .action {
    display: flex;
  }

  .original-price {
    margin-left: 10px;
    color: #999;
    text-decoration: line-through;
  }

  .thumbnail {
    width: 50px;
    height: 50px;
    border-radius: 0.4em;
  }

  .flex-goods {
    margin: 10px;
    display: flex;

    align-items: center;

    > img {
      margin-right: 10px;
    }
  }

  .tips {
    color: #999;
    font-size: 12px;
  }

  .goods-table {
    width: 1000px;
    margin: 10px 0;
  }

  .upload-list {
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }

  .upload-list img {
    width: 100%;
    height: 100%;
  }

  .upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }

  .upload-list:hover .upload-list-cover {
    display: block;
  }

  .upload-list-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
